长按控件弹出上下文菜单(结合选项菜单)

1. 我们可以点击控件或者长按控件的方式来弹出,比较常用的是长按控件弹出上下文菜单,这里的控件可以是TextView,Button,EditText等等,下面是具体长按TextView与EditView弹出上下文菜单的例子:

2. 思路分析:

① 首先需要在布局文件中声明多个TextView与EditText控件,规定相应的id属性方便在MainActivity中通过findViewById方法来获取相应的控件对象

② 为需要长按弹出上下文菜单的控件来注册上下文菜单,注册之后长按这些控件就会弹出上下文菜单

private void registerForWidget() {
    	registerForContextMenu(username);
    	registerForContextMenu(password);
    	registerForContextMenu(account);
    	registerForContextMenu(userTextView);
    	registerForContextMenu(accountTextView);
    	registerForContextMenu(passwordTextView);
    	registerForContextMenu(birthdayTv);
    	registerForContextMenu(hobitsTv);
}

③ 重写Activity的onCreateContextMenu方法来创建上下文菜单,在这个方法中可以创建相应的菜单项,下面是添加菜单项的方法,第一个参数是组id,第二个参数是菜单项的id,第三项是是否排序,第四项是将要显示的内容

menu.add(0, 1, 0, "白");
menu.add(0, 2, 0, "浅红");
menu.add(0, 3, 0, "浅绿");
menu.add(0, 4, 0, "浅篮");

④ 重写Activity的onContextItemSelected方法,因为我们需要对点击菜单项之后进行相应的操作,所以需要重写这个方法来实现我们点击事件之后的操作,在方法中我们可以获取到点击的上下文菜单是哪一项然后我们对其进行相应的操作

⑤ 在页面中还需要实现一个选项菜单,需要重写Activity的onCreateOptionsMenu方法,方法中规定需要添加的菜单有哪些,下面是具体添加菜单项的方法:

MenuItem clear = menu.add(1, 1, 2, "清空各选项"); 
MenuItem logout = menu.add(2, 2, 3, "退出");

3. 下面是具体实现的代码:

布局文件backgroundset.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/color">
    <!-- 注意线性布局进行嵌套的时候多个线性布局的高度为wrap_content不能够是match_parent这样的话高度
    	全是这个线性布局了-->
    <!--  第一个控件-->
	<LinearLayout 
	   	android:layout_width="match_parent"
    	android:layout_height="wrap_content"
    	android:orientation="horizontal"
    	android:layout_marginTop="20dp"
	    android:layout_marginLeft="20dp">
	    <TextView
	        android:id="@+id/usernameTv"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:text="@+string/username" 
	        android:textSize="20sp"/>
	    <EditText 
	        android:id="@+id/username"
		    android:layout_width="fill_parent"
	        android:layout_height="wrap_content"
	        android:hint=""
	        android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ"/>
	</LinearLayout>
	  
	<!--  第二个控件-->
	<LinearLayout 
	   	android:layout_width="match_parent"
    	android:layout_height="wrap_content"
    	android:orientation="horizontal"
    	android:layout_marginTop="20dp"
	    android:layout_marginLeft="20dp">
	    <TextView
	        android:id="@+id/accountTv"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:text="@+string/account" 
	        android:textSize="20sp"/>
	    <EditText 
	        android:id="@+id/account"
		    android:layout_width="fill_parent"
	        android:layout_height="wrap_content"
	        android:hint=""/>
	</LinearLayout>
	
	<!--  第三个控件-->
	<LinearLayout 
	   	android:layout_width="match_parent"
    	android:layout_height="wrap_content"
    	android:orientation="horizontal"
    	android:layout_marginTop="20dp"
	    android:layout_marginLeft="20dp">
	    <TextView
	        android:id="@+id/passwordTv"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:text="@+string/password" 
	        android:maxLength="12"
	        android:textSize="20sp"/>
	    <EditText 
	        android:id="@+id/password"
	        android:inputType="textPassword"
		    android:layout_width="fill_parent"
	        android:layout_height="wrap_content"
	        android:hint=""/>
	</LinearLayout>

	<!--  第四个控件-->
	<!--android:gravity="center"要放在布局中可以使得单选按钮居中  -->
	<RadioGroup 
	    android:id="@+id/RadioGroup"
	   	android:layout_width="match_parent"
    	android:layout_height="wrap_content"
    	android:orientation="horizontal"
    	android:layout_marginTop="20dp"
	    android:layout_marginLeft="19dp">
	   <TextView
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:text="@+string/gender" 
	        android:textSize="20sp"/>
	   <RadioButton 
	       android:checked="true"
	       android:id="@+id/male"
	       android:textSize="20sp"
	       android:text="@+string/male"/>
	   <RadioButton 
	       android:id="@+id/female"
	       android:layout_marginLeft="20dp"
	       android:textSize="20sp"
	       android:text="@+string/female"/>
	</RadioGroup>	
	
	<LinearLayout 
	   	android:layout_width="match_parent"
    	android:layout_height="70dp"
    	android:orientation="horizontal">
	    <TextView 
	        android:id="@+id/birthdayTv"
	        android:layout_marginTop="20dp"
	      	android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:textSize="20sp"
    		android:layout_marginRight="10dp"
    		android:text="@+string/birthdatShow"/>
	     <TextView 
	        android:layout_marginTop="20dp"
	        android:id="@+id/birthdatShowTv"
	      	android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:layout_marginRight="5dp"
    		android:textSize="20sp"
    		android:text=""/>
	    <Button 
	        android:id="@+id/birthdayInput"
	        android:layout_marginTop="3dp"
	      	android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:layout_gravity="center"
    		android:background="@drawable/birthdayset"
    		android:text="@+string/birthdayInput"/>
	</LinearLayout>
	
	<!-- 第六个控件 -->
	<LinearLayout 
	   	android:layout_width="match_parent"
    	android:layout_height="wrap_content"
    	android:orientation="horizontal"
    	android:layout_marginTop="18dp"
	    android:layout_marginLeft="20dp">
	    <TextView
	        android:id="@+id/hobitsTv"
	        android:layout_marginTop="50dp"
	        android:layout_marginRight="60dp"
	        android:layout_width="wrap_content"
	        android:layout_height="30dp"
	        android:text="@+string/hobits" 
	        android:textSize="20sp"/>
	    <LinearLayout 
	        android:layout_width="match_parent"
	    	android:layout_height="wrap_content"
	    	android:orientation="vertical">
		    <CheckBox 
		        	android:id="@+id/swimming"
			        android:layout_width="wrap_content"
			        android:layout_height="30dp"
			        android:text="@+string/swimming"
			        android:checked="true" 
			        android:textSize="20sp"/>
		    <CheckBox 
		        android:id="@+id/balls"
		        android:layout_width="wrap_content"
		        android:layout_height="30dp"
		        android:checked="true" 
		        android:text="@+string/balls" 
		        android:textSize="20sp"/>
		    <CheckBox 
		        android:id="@+id/runs"
		        android:layout_width="wrap_content"
		        android:layout_height="30dp"
		        android:text="@+string/runs" 
		        android:textSize="20sp"/>
		    <CheckBox 
		        android:id="@+id/climb"
		        android:layout_width="wrap_content"
		        android:layout_height="30dp"
		        android:text="@+string/climb" 
		        android:textSize="20sp"/>
		 </LinearLayout>
	</LinearLayout>
		
	<!-- 第七个控件 -->
	<LinearLayout 
	   	android:layout_width="match_parent"
    	android:layout_height="wrap_content"
    	android:orientation="horizontal"
    	android:gravity="center"
    	android:layout_marginTop="20dp"
	    android:layout_marginLeft="10dp">
	    <Button 
	        android:id="@+id/registerBtn"
	      	android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="@string/registerBtn"
			android:background="@drawable/registerbtn"/>
	</LinearLayout>
</LinearLayout>

注册成功之后跳转到的success.xml页面:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal"
    android:orientation="vertical" >
    <TextView 
        android:id="@+id/success"
        android:layout_width="wrap_content"
    	android:layout_height= "wrap_content"
    	android:gravity="center_horizontal"
    	android:text="@+string/success"
  		android:layout_marginTop="200sp"
  		android:layout_marginLeft="150sp"
        />
</LinearLayout>

布局文件相关的TextView的文本值的资源文件设置:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="username">&#160;用户名&#160;:</string>
    <string name="account">&#160;&#160;&#160;账&#160;&#160;号&#160;:</string>
    <string name="password">&#160;&#160;&#160;密&#160;&#160;码&#160;:</string>
    <string name="gender">&#160;&#160;&#160;性&#160;&#160;别&#160;:</string>
    <string name="male">男</string>
    <string name="female">女</string>
    <string name="hobits">&#160;爱&#160;&#160;&#160;好&#160;:&#160;</string>
    <string name="swimming">游泳</string>
    <string name="birthdatShow">&#160;日期输入&#160;:</string>
    <string name="balls">球类</string>
    <string name="runs">慢跑</string>
    <string name="birthdayInput">点击设置</string>
    <string name="climb">爬山</string>
    <string name="registerBtn">注册</string>
    <string name="success">用户注册成功!</string>
</resources>

配置切换mainActivity页面背景颜色的资源文件:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
  <drawable name="white">#FFFFFF</drawable>
  <drawable name="lightred">#FF3366</drawable>
  <drawable name="lightgreen">#00FF66</drawable>
  <drawable name="lightblue">#666FFF</drawable>
</resources>

布局文件中圆角按钮的布局设置:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <solid android:color="#99CCCC" />
    <corners android:radius="13dip" />
    <padding
        android:bottom="10dp"
        android:left="10dp"
        android:right="10dp"
        android:top="10dp" />
    </shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <solid android:color="#99CCCC" />
    <corners android:radius="15dip" />
    <padding
        android:bottom="10dp"
        android:left="10dp"
        android:right="10dp"
        android:top="10dp" />
    </shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
 
    <!-- 填充的颜色 -->
    <solid android:color="#6495ED" />
 
    <!-- 设置按钮的四个角为弧形 -->
    <!-- android:radius 弧形的半径 -->
    <corners android:radius="15dip" />
 
    <!-- padding:Button里面的文字与Button边界的间隔 -->
    <padding
        android:bottom="10dp"
        android:left="10dp"
        android:right="10dp"
        android:top="10dp" />
    </shape>

MainActivity:

package com.example.exp4;
import java.util.Calendar;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("CutPasteId")
public class MainActivity extends Activity {
	EditText username;
	EditText account;
	EditText password;
	TextView userTextView;
	TextView accountTextView;
	TextView passwordTextView;
	TextView birthdayTv;
	TextView birthdatShowTv;
	TextView hobitsTv; 
	EditText brithday;
	RadioButton male;
	Button registerBtn;
	RadioGroup radioGroup;
	CheckBox swimming;
	CheckBox balls;
	CheckBox runs;
	CheckBox climb;
	Button birthdayInput;
	int checkBoxCount = 2;
	Menu mMenu;
	String s = "";
    @SuppressLint("SimpleDateFormat")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        getObject();
        registerForWidget();
        CompoundButton.OnCheckedChangeListener checkBoxesListener =
        	new CompoundButton.OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(CompoundButton compoundButton,
					boolean checked) {
				if(checked){
					if(++checkBoxCount > 2){
						Toast toast = Toast.makeText(getApplicationContext(), "兴趣不能超过两项", Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, -50, 100);
						toast.show();
						compoundButton.setChecked(false);
						checkBoxCount--;
						return;
					}
				}else{
					checkBoxCount--;
				}
			}			
        };

        birthdayInput.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Calendar calendar = Calendar.getInstance(Locale.CHINA);
				int curYear = calendar.get(Calendar.YEAR);
				int curMonth = calendar.get(Calendar.MONTH);;
				int curDay = calendar.get(Calendar.DAY_OF_MONTH);
				DatePickerDialog datePickerDialog = new DatePickerDialog(
				MainActivity.this, myOnDataCaptureListener, curYear, curMonth, curDay);
				datePickerDialog.show();
			}

			DatePickerDialog.OnDateSetListener myOnDataCaptureListener = 
				new DatePickerDialog.OnDateSetListener() {
				@Override
				public void onDateSet(DatePicker view, int year,
						int monthOfYear, int dayOfMonth) {
					s = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
					birthdatShowTv.setText(s);
				}
			};
		});	

        swimming.setOnCheckedChangeListener(checkBoxesListener);;
        balls.setOnCheckedChangeListener(checkBoxesListener);
        runs.setOnCheckedChangeListener(checkBoxesListener);
        climb.setOnCheckedChangeListener(checkBoxesListener);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
			}
		});	
  		
        registerBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				username = (EditText) findViewById(R.id.username);
				String str = username.getText().toString();
				if(str == null || str.equals("")){
					showMessage("请输入用户名");
					return;
				}
				if(str.length() <= 4){
					showMessage("用户名长度必须大于4位");
					return;
				}
				account = (EditText) findViewById(R.id.account);
				str = account.getText().toString();
				if(str == null || str.equals("")){
					showMessage("请输入您的账号");
				}
				if(str.length() <= 6){
					showMessage("账号长度必须大于6位");
					return;
				}
				password = (EditText) findViewById(R.id.password);
				str = password.getText().toString();
				if(str == null || str.equals("")){
					showMessage("请输入您的密码");
				}
				if(str.length() < 4 || str.length() > 12){
					showMessage("密码长度必须在4~12位之间");
					return;
				}
				if(s.equals("")){
					showMessage("请设置出生日期");
					return;
				}	
				showMessage(username.getText().toString() + "注册成功");
				Intent register = new Intent(MainActivity.this, Success.class);
				startActivity(register);
			}
			
			public void showMessage(String s) {
				Toast toast = Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 100);
				toast.show();
			}
		});
    }
    
    private void getObject() {
    	username =  (EditText) findViewById(R.id.username);
        password =  (EditText) findViewById(R.id.password);
        account =  (EditText) findViewById(R.id.account);
        radioGroup = (RadioGroup) findViewById(R.id.RadioGroup);
        registerBtn = (Button) findViewById(R.id.registerBtn);
        swimming = (CheckBox) findViewById(R.id.swimming);
        balls = (CheckBox) findViewById(R.id.balls);
        runs = (CheckBox) findViewById(R.id.runs);
        climb = (CheckBox) findViewById(R.id.climb);
        birthdayInput = (Button) findViewById(R.id.birthdayInput);
		userTextView = (TextView) findViewById(R.id.usernameTv);
		accountTextView = (TextView) findViewById(R.id.accountTv);
		passwordTextView = (TextView) findViewById(R.id.passwordTv);
		birthdayTv = (TextView) findViewById(R.id.birthdatShowTv);
		hobitsTv = (TextView) findViewById(R.id.hobitsTv);
		birthdatShowTv = (TextView) findViewById(R.id.birthdatShowTv);
		male = (RadioButton) findViewById(R.id.male);
	}

    private void registerForWidget() {
    	registerForContextMenu(username);
    	registerForContextMenu(password);
    	registerForContextMenu(account);
    	registerForContextMenu(userTextView);
    	registerForContextMenu(accountTextView);
    	registerForContextMenu(passwordTextView);
    	registerForContextMenu(birthdayTv);
    	registerForContextMenu(hobitsTv);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		mMenu = menu;
		MenuItem clear = menu.add(1, 1, 2, "清空各选项"); 
		MenuItem logout = menu.add(2, 2, 3, "退出");
		clear.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {	
				//一定要加上这个否则在清空的时候会出现问题
				checkBoxCount = 0;
				username.setText("");
				password.setText("");
				account.setText("");
				birthdatShowTv.setText("");
				swimming.setChecked(true);
				balls.setChecked(true);
				runs.setChecked(false);
				climb.setChecked(false);
				male.setChecked(true);
				//最后恢复为2
				checkBoxCount = 2;
				return false;
			}	   
	   }); 
		
		logout.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				System.exit(0);
				return false;
			}	   
	   }); 
	    return true;
	}
    
    @SuppressLint("ShowToast") @Override
    public void onCreateContextMenu(android.view.ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	menu.add(0, 1, 0, "白");
    	menu.add(0, 2, 0, "浅红");
    	menu.add(0, 3, 0, "浅绿");
    	menu.add(0, 4, 0, "浅篮");
    };  
    
    @SuppressWarnings("deprecation")
	@Override
    public boolean onContextItemSelected(MenuItem item) {
    	LinearLayout linearLayout = null;
    	switch(item.getItemId()){
    		case 1 :
    			linearLayout = (LinearLayout) findViewById(R.id.color);
    			linearLayout.setBackgroundColor(getResources().getColor(R.drawable.white));
    			break;
    		case 2 :
    			linearLayout = (LinearLayout) findViewById(R.id.color);
    			linearLayout.setBackgroundColor(getResources().getColor(R.drawable.lightred));
    			break;	
    		case 3 :
    			linearLayout = (LinearLayout) findViewById(R.id.color);
    			linearLayout.setBackgroundColor(getResources().getColor(R.drawable.lightgreen));
    			break;
    		case 4 :
    			linearLayout = (LinearLayout) findViewById(R.id.color);
    			linearLayout.setBackgroundColor(getResources().getColor(R.drawable.lightblue));
    			break;
    	}
    	return super.onContextItemSelected(item);
    } 
}

注册成功之后跳转到的另外一个Success类:

package com.example.exp4;
import android.os.Bundle;
import android.widget.TextView;
public class Success extends MainActivity{
	TextView success;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.success);
		success = (TextView) findViewById(R.id.success);
	}
}

项目目录结构:

此外还需要在AndroidManifest.xml规定需要跳转到的类:

<activity android:name="com.example.exp4.Success"/>

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值