Вызов метода из другого действия из действия - PullRequest
3 голосов
/ 14 марта 2011

Я знаю, что мы не можем вызвать метод из действия, которое находится в другом действии. Я пытаюсь найти лучший способ обойти это.

Вот мой код. Это метод, который я пытаюсь вызвать. Это в моей ScoreCard активности.

public void numPlayerSetup(){
{
    int[] ids = {
        R.id.TextView11, R.id.TextView12, R.id.TextView13
    };

    for(int i : ids) {
        TextView tv = (TextView)findViewById(i);
        tv.setVisibility(View.INVISIBLE);
    }

}

Вот как я пытаюсь вызвать метод. score является объектом класса ScoreCard.

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
    int item = spinner.getSelectedItemPosition();


    if(item==1){
        Log.i("error","This Sucks");
        score.numPlayerSetup();
    }
}

Я пытался поместить метод numPlayerSetup в другой класс, который не расширяет Activity, просто содержит логику, но я не могу использовать метод findViewById() без расширения активности.

Вот как я это называю.

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
    int item = spinner.getSelectedItemPosition();
    ArrayList<TextView> myTextViewList = new ArrayList<TextView>();

    TextView tv1 = (TextView)findViewById(R.id.TextView14);
    myTextViewList.add(tv1);

    if(item==1){
        Log.i("error","This Sucks");
        Setup.numPlayerSetup(myTextViewList);
    }

Тогда это класс, который я называю.

public class Setup {
    TextView tv;

    public static void numPlayerSetup(ArrayList<TextView> tvs){
        for(TextView tv : tvs) {
            Log.i("crash","This Sucks");
            tv.setVisibility(View.INVISIBLE);  //this line is highlighted in the debugger as the line my error is coming from
        }    
    }
}

Он регистрирует сообщение в logcat и дает мне исключение нулевого указателя. Отладчик говорит, что значение для телевизора является нулевым. Поэтому я получаю исключение нулевого указателя?

Ответы [ 3 ]

5 голосов
/ 14 марта 2011

Вы можете просто создать класс Utitlity (не Activity) и передать текстовые представления, которые вы хотите изменить.и вызывайте этот метод всякий раз, когда вам это нужно.

public class Setup {

public static void numPlayerSetup(ArrayList<TextView> tvs){

                 for(TextView tv : tvs) {
                            tv.setVisibility(View.INVISIBLE);
                        }    
             }
}

Затем вы можете использовать его как (в Activity):

ArrayList<TextView> myTextViewList = new ArrayList<TextView>();
TextView tv1 = (TextView)findViewById(R.id.tv1);
myTextViewList.add(tv1);


    Setup.numPlayerSetup(myTextViewList);
1 голос
/ 14 марта 2011

Создайте класс, расширяющий Activity

public class ScoreCard extends Activity{ 
 // ...   
public void numPlayerSetup(){  
        {  
             int[] ids = {  
                        R.id.TextView11, R.id.TextView12, R.id.TextView13
                    };

                    for(int i : ids) {
                        TextView tv = (TextView)findViewById(i);
                        tv.setVisibility(View.INVISIBLE);
                    }

                 }
             }
}

Теперь, если вы хотите создать Activity и вызывать метод, просто продлите ScoreCard

public class AnotherActivity extends ScoreCard{  
  // ...  

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
        int item = spinner.getSelectedItemPosition();


        if(item==1){
            Log.i("success","This Rocks");
            numPlayerSetup();

    }
    }  

}

Надеюсь, это ответит на ваш вопрос.

0 голосов
/ 26 августа 2013

вызов действия из другого действия

main.xml

<RelativeLayout 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" >

<TextView
    android:id="@+id/textView14"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="14dp"
    android:text="Textview 4"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
    android:id="@+id/textView11"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:text="Textview 1"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
    android:id="@+id/textView12"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView11"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="53dp"
    android:text="Textview 2"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
    android:id="@+id/textView13"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView14"
    android:layout_marginTop="30dp"
    android:text="textview 3"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/textView14"
    android:layout_marginLeft="26dp"
    android:layout_toRightOf="@+id/textView14"
    android:ems="10" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView13"
    android:layout_alignBottom="@+id/textView13"
    android:layout_alignLeft="@+id/editText1"
    android:ems="10" />

<EditText
    android:id="@+id/editText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/editText2"
    android:layout_alignTop="@+id/textView12"
    android:ems="10" />

<EditText
    android:id="@+id/editText4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/editText3"
    android:layout_centerVertical="true"
    android:ems="10" />

main1.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

<RelativeLayout
              android:layout_width="fill_parent"
              android:layout_height="wrap_content">

    <TextView android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is screen 2 called from activity scorecard."/>



</RelativeLayout>>

ScoreCard.java

package com.example.score.card;


public class ScoreCard extends Activity {

TextView textview1, textview2, textview3;
EditText editText1, editText2, editText3;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    onItemSelected();
}

private void onItemSelected() {
     textview1 = (TextView) findViewById(R.id.textView11);
     textview2 = (TextView) findViewById(R.id.textView12);
     textview3 = (TextView) findViewById(R.id.textView13);
     editText1 = (EditText) findViewById(R.id.editText1);
     editText2 = (EditText) findViewById(R.id.editText2);
     editText3 = (EditText) findViewById(R.id.editText3);
     setOnclickListener(textview1);
     setOnclickListener(textview2);
     setOnclickListener(textview3);     
}

private void setOnclickListener(final TextView textview12) {
    // TODO Auto-generated method stub
    textview12.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // Toast.makeText(getApplicationContext(),
            // textview12+" is selected", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(getApplicationContext(), ScoreCard2.class);
            intent.putExtra("editText1", editText1.getText().toString());
            intent.putExtra("editText2", editText2.getText().toString());
            intent.putExtra("editText3", editText3.getText().toString());
            startActivity(intent);
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
}

ScoreCard2.java

package com.example.score.card;


public class ScoreCard2 extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main1);
    onItemSelected();
}

 private void onItemSelected() {
        // TODO Auto-generated method stub          
         String strText1 = getIntent().getStringExtra("editText1");
         String strText2 = getIntent().getStringExtra("editText2");
         String strText3 = getIntent().getStringExtra("editText3");
         setOnclickListener(strText1);
         setOnclickListener(strText2);
         setOnclickListener(strText3);      
    }
private void setOnclickListener(String textview12) {
    // TODO Auto-generated method stub
     Toast.makeText(getApplicationContext(),
     textview12+" is selected", Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    return super.onCreateOptionsMenu(menu);
}
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.score.card"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".ScoreCard"
        android:label="@string/title_activity_score_card" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
      <activity android:name=".ScoreCard2"></activity>
</application>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...