簡體   English   中英

如何將按鈕鏈接到 Android 中的其他 xml?

[英]How to link a button to other xml in Android?

如何在 Android 中鏈接按鈕?

例如在主頁中有 2 個按鈕:'Item1 & item2'

我需要輸入代碼,以便我可以單擊“項目”按鈕,然后將顯示 Item1 數據......

這是我當前在 Activity.java 上的代碼:

    package com.example.myshops;

    import java.text.SimpleDateFormat;
    import java.util.Calendar;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    import android.app.ActionBar;
    import android.app.Fragment;
    import android.os.Bundle;
    import android.view.Gravity;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.Display;
    import android.view.WindowManager;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.os.Build;

    public class MainActivity extends Activity implements OnClickListener  {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);



            FragmentManager fragmentManager=getFragmentManager();
            FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction(); 
            Home_fragment hf=new Home_fragment();
            fragmentTransaction.replace(android.R.id.content, hf);
            fragmentTransaction.commit();

            setContentView(R.layout.activity_main);

            Button item1Click = (Button)findViewById(R.id.Item1Button);
            itemClick1.setOnClickListener(this);

            Button item2Click = (Button)findViewById(R.id.Item2Button);
            itemClick2.setOnClickListener(this);

            Button item3Click = (Button)findViewById(R.id.Item3Button);
            itemClick3.setOnClickListener(this);


            Calendar c = Calendar.getInstance();
            System.out.println("Current time => "+c.getTime());

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = df.format(c.getTime());
            // formattedDate have current date/time
            Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();


          // Now we display formattedDate value in TextView
            TextView txtView = new TextView(this);
            txtView.setText("Current Date and Time : "+formattedDate);
            txtView.setGravity(Gravity.CENTER);
            txtView.setTextSize(20);
            setContentView(txtView);


        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        /**
         * A placeholder fragment containing a simple view.
         */

        public static class PlaceholderFragment extends Fragment {

            public PlaceholderFragment() {
            }

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.fragment_main, container, false);
                return rootView;
            }



            public void item1Click(View view) {
                FragmentManager fragmentManager=getFragmentManager();
                FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();     
                Item1_fragment hf=new Item1_fragment();
                fragmentTransaction.replace(android.R.id.content, hf);
                fragmentTransaction.commit();
            }   


        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


 switch(v.getId())
      {
       case R.id.Item1Button:

         break;
       case R.id.Item2Button:

         break;
       case R.id.Item3Button:

         break;     
       }

        }


        }

我的 home.xml(例如):

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.myshops.MainActivity"
        tools:ignore="MergeRootFrame" >

        <Button
            android:id="@+id/Item2Button"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/Item2Button"
            android:onClick="item2Click"
            android:text="@string/Item2" />

        <Button
            android:id="@+id/Item3Button"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/Item2Button"
            android:onClick="item3Click"
            android:text="@string/Item3" />


        <Button
            android:id="@+id/Item1Button"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:onClick="item1Click"
            android:text="@string/Item1" />

        <Button
            android:id="@+id/PrevButton"
            android:layout_width="110dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:text="@string/Previous" />

        <Button
            android:id="@+id/HomeButton"
            android:layout_width="110dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:text="@string/Home" />

        <Button
            android:id="@+id/NextButton"
            android:layout_width="85dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:text="@string/Next" />



    </RelativeLayout>

我的日志中的錯誤:

04-11 15:56:54.915: D/dalvikvm(547): Not late-enabling CheckJNI (already on)
04-11 15:56:56.145: D/AndroidRuntime(547): Shutting down VM
04-11 15:56:56.155: W/dalvikvm(547): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
04-11 15:56:56.165: E/AndroidRuntime(547): FATAL EXCEPTION: main
04-11 15:56:56.165: E/AndroidRuntime(547): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.s0237600_diary/com.example.myshops.MainActivity}: java.lang.NullPointerException
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.os.Looper.loop(Looper.java:137)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.ActivityThread.main(ActivityThread.java:4340)
04-11 15:56:56.165: E/AndroidRuntime(547):  at java.lang.reflect.Method.invokeNative(Native Method)
04-11 15:56:56.165: E/AndroidRuntime(547):  at java.lang.reflect.Method.invoke(Method.java:511)
04-11 15:56:56.165: E/AndroidRuntime(547):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-11 15:56:56.165: E/AndroidRuntime(547):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-11 15:56:56.165: E/AndroidRuntime(547):  at dalvik.system.NativeStart.main(Native Method)
04-11 15:56:56.165: E/AndroidRuntime(547): Caused by: java.lang.NullPointerException
04-11 15:56:56.165: E/AndroidRuntime(547):  at com.example.myshops.MainActivity.onCreate(MainActivity.java:44)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.Activity.performCreate(Activity.java:4465)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-11 15:56:56.165: E/AndroidRuntime(547):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
04-11 15:56:56.165: E/AndroidRuntime(547):  ... 11 more
04-11 15:56:58.955: I/Process(547): Sending signal. PID: 547 SIG: 9
04-11 15:57:02.035: D/AndroidRuntime(565): Shutting down VM
04-11 15:57:02.035: W/dalvikvm(565): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
04-11 15:57:02.055: E/AndroidRuntime(565): FATAL EXCEPTION: main
04-11 15:57:02.055: E/AndroidRuntime(565): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myshops/com.example.myshops.MainActivity}: java.lang.NullPointerException
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.os.Looper.loop(Looper.java:137)
04-11 15:57:02.055: E/AndroidRuntime(565):  at android.app.ActivityThread.main(ActivityThread.java:4340)
04-11 15:57:02.055: E/AndroidRuntime(565):  at java.lang.reflect.Method.invokeNative(Native Method)

您應該在代碼或 xml 中定義單擊偵聽器,而不是兩者。 刪除其中一個,另一個應該可以工作。

Onclicklistener 喜歡

 Button item1Click = (Button)findViewById(R.id.Item1Button);

 item1Click.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    };

和其他按鈕一樣

做這個

    @Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    //check here that to which view does v match for example
    if(v==item1Click)
        {
            //then do something
        }
} 

否則你可以刪除那個實現的東西並為每個按鈕創建單獨的監聽器,如 raj 所述

使用單擊偵聽器訪問所有Button單擊偵聽器,並使用按鈕的 id 並實現每個點擊事件,如下所示:

 @Override
public void onClick(View v) {
    // TODO Auto-generated method stub

  switch(v.getId())
  {
   case R.id.Item1Button:
     //write your logic
     break;
   case R.id.Item2Button:
     //write your logic
     break;
   case R.id.Item3Button:
     //write your logic
     break;     
   }
}

我說的是一種解決問題的方法,還有其他方法可以解決問題

<Button
        android:id="@+id/Item3Button"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/Item2Button"
        android:onClick="item3Click"
        android:text="@string/Item3" />

在這里你寫了android:onClick="item3Click" ,對於所有按鈕,

所以在 java 代碼中你可以這樣寫

 public void item3Click(View view){

    //what ever you want to do in the button 3 click 
    }
 public void item2Click(View view){

    //what ever you want to do in the button 2 click 
    }
 public void item1Click(View view){

    //what ever you want to do in the button 1 click 
    }

對所有按鈕重復相同的操作,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM