У меня есть приложение с несколькими кнопками в первом действии. Кнопка завершения была настроена для открытия второго действия при нажатии. Я хочу иметь возможность просматривать текст на других кнопках во втором действии при нажатии. Я ранее устанавливал onclicklistener на всех кнопках в первом действии, а затем называл протокол onclick во втором действии следующим образом:
public void onClick(View v) {
((Button) v).getText();
}
Но это не сработает. Мне просто интересно, правильно ли я делаю это, вызывая протокол onClick во втором действии, и если не так, как это сделать. Я также пробовал этот код:
public void onClick(View v) {
// 1) Possibly check for instance of first
Button b = (Button)v;
String buttonText = b.getText().toString();
}
Спасибо за помощь.
Вот код для первого действия, в котором присутствуют все кнопки:
package com.example.coursework1;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.Button;
import android.view.View;
public class MainActivity extends Activity implements View.OnClickListener {
Button button7;
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button7 = (Button)findViewById(R.id.button7);
button7.setOnClickListener(this);
//
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
@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;
}
private void FinishClick()
{
startActivity(new Intent("com.example.coursework1"));
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button7:
FinishClick();
break;
}
// TODO Auto-generated method stub
}
}
И вот его.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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/button1"
android:layout_marginRight="68dp"
android:text="@string/Panini" />
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="41dp"
android:layout_toRightOf="@+id/textView1"
android:text="@string/Tea" />
<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginTop="49dp"
android:layout_toRightOf="@+id/textView1"
android:text="@string/Sandwich" />
<Button
android:id="@+id/button4"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button3"
android:layout_alignBottom="@+id/button3"
android:layout_alignLeft="@+id/button2"
android:text="@string/Salad" />
<Button
android:id="@+id/button5"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button3"
android:layout_below="@+id/button3"
android:layout_marginTop="48dp"
android:text="@string/Water" />
<Button
android:id="@+id/button6"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button4"
android:layout_alignTop="@+id/button5"
android:text="@string/Juice" />
<Button
android:id="@+id/button7"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"
android:text="@string/Finish" />
</RelativeLayout>
Код для второго действия:
package com.example.coursework1;
import android.app.Activity;
import android.os.Bundle;
public class FinishButton extends Activity{
@Override
protected void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.finish_button);
}
public void onClick(View v) {
((Button) v).getText();
}
}
В момент нажатия кнопки7 открывается второе действие при нажатии. Я также хочу просмотреть текст того, что другие кнопки будут нажаты во втором действии.
Я написал Android Vapor, который представляет собой небольшую структуру, которая обеспечивает абстракции по сравнению с обычными API-интерфейсами, чтобы сделать такие задачи проще. Поэтому в вашем случае, чтобы построить свое намерение:
$.Intent(this, FinishButton.class).put("buttonText", buttonText);
// NOTE: 'this' is a context handle, so your current activity in this case
Затем в вашей деятельности FinishButton
:
protected void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.finish_button);
String buttonText = $.Intent(getIntent()).extras().getString("buttonText");
}
Также в VaporBundle
и VaporIntent
метод .put()
перегружен, поэтому вы можете использовать любой поддерживаемый тип :)
Попробуйте, если хотите, все бесплатно, и источник доступен.
В вашей MainActivity
Объявите HashSet глобально в вашем MainActiviy
private HashSet<String> hashSet;
Добавьте это в свой onCreate
hashSet = new HashSet<String>();
Этот метод является реализацией View.OnClickListener
onClick
методы
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
hashSet.add("BUTTON1");
break;
case R.id.button2:
hashSet.add("BUTTON2");
break;
case R.id.button3:
hashSet.add("BUTTON3");
break;
// Do the same for remaining buttons
case R.id.button7:
Intent intent = new Intent("com.example.coursework1");
intent.putExtra("BUTTONS_DATA", hashSet);
startActivity(intent);
break;
}
И в вашем FinishButton
вы получите HashSet
и вы можете получить данные, на которые нажаты кнопки... через строки
Bundle extras = getIntent().getExtras();
if (extras != null) {
HashSet<String> hashSet = (HashSet<String>) extras
.get("BUTTONS_DATA");
System.out.println("These buttons are clicked in the FirstActvity");
for (String string : hashSet) {
System.out.println(string);
}
}
Вы можете передать эту простую строку через само замысел
Intent newintent=new Intent(getApplicationContext(), NextActivity.class);
newintent.putExtra("type", 1);
startActivity(resturatntintent);
on NextActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
type=getIntent().getExtras().getInt("type", 0);
....
}
редактировать:
Intent newintent=new Intent(getApplicationContext(), NextActivity.class);
newintent.putExtra("type", 1);
startActivity(newintent);