如何使用操作按钮更改活动?
package com.com.com;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class HomeFragment extends Fragment {
public HomeFragment(){}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//In order for this method to receive calls
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_new1:
Button switchButton = (Button) findViewById(R.id.btnsignin);
switchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeFragment.this, Login.class);
startActivity(intent);
}
});
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
这是我目前的代码,但它似乎不起作用。有人可以解释一下如何使这个工作?我知道我需要这个
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_new1:
openSearch();
return true;
default:
return super.onOptionsItemSelected(item);
}
但是如果我需要用转换代码替换openSearch
,我就不会这样做。任何帮助都会很棒。
答案 0 :(得分:3)
为什么你需要使用那个按钮!
必须在没有任何按钮的情况下工作:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_new1:
Intent intent = new Intent( getActivity(), Login.class);
getActivity().startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}