我有一個導航抽屜和一個生成產品列表的片段。問題是,當我點擊某個產品時,它會嘗試在基本活動中找到onClick方法,而不是在片段的java類中。我應該在基本活動中實現onClick方法還是有任何方法在fragment類中實現它?我應該在NavigationDrawer活動中實現onClick方法?
這是產品的佈局 「item_order.xml」:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:onClick="orderClick"
android:id="@+id/tOrder"
android:padding="4dp">
....
</RelativeLayout>
這是基礎類:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waiter);
//set fragment
OrdersFragment fragment=new OrdersFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
OrdersFragment.wa=this;
}
這裏的片段:
public class OrdersFragment extends Fragment {
private Database db;
private ArrayList<Order> orders=new ArrayList<Order>();
private OrderAdapter adapter;
private ListView listOrders;
public static WaiterActivity wa;
public OrdersFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_orders, container, false);
// Inflate the layout for this fragment
db = new Database();
db.createNewOrderListener(this);
ListView listOrders = (ListView) view.findViewById(R.id.ordersList);
adapter = new OrderAdapter(this.getContext(), R.layout.item_order, orders);
listOrders.setAdapter(adapter);
return view;
}
請粘貼您的完整代碼。 –
如果只有一個xml對象正在使用onClick方法,請避免使用xml中的onclick,並使用.java一側的setOnClickListener。原因是:onClick搜索鏈接到xml的java中的方法,而不是遍佈整個應用程序。順便說一句,發佈完整的代碼@BhavinShah說 –
請確保您使用正確的LayoutInflater。 – Qamar