새 활동을 시작하는 방법 버튼 클릭
Android 응용 프로그램에서 다른 활동의 단추를 클릭할 때 새 활동(GUI)을 시작하는 방법과 이 두 활동 간에 데이터를 전달하는 방법은 무엇입니까?
만만하다.
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
다른 쪽에서는 다음을 통해 추가 정보를 검색할 수 있습니다.
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
}
AndroidManifest.xml에 새 활동을 추가하는 것을 잊지 마십시오.
<activity android:label="@string/app_name" android:name="NextActivity"/>
현재 반응은 좋지만 초보자들에게는 좀 더 포괄적인 답변이 필요합니다.하는 방법은 세, Android를 합니다. » » » » » » » » »Intent
class; 의도 | 안드로이드 개발자.
-
onClick
버튼의 속성. (시작) - 할당
OnClickListener()
익명의 수업을 통해.(중간) - 활범방법인스이터페위동는을 Wide
switch
진술아 (" 아님) ("Pro" 님)님)
다음은 당신이 따라가고 싶다면 제 예에 대한 링크입니다.
-
onClick
버튼의 속성. (시작)
단추에 다음이 있습니다.onClick
파일: .xml 파일:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="goToAnActivity"
android:text="to an activity" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="goToAnotherActivity"
android:text="to another activity" />
Java 클래스:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
public void goToAnActivity(View view) {
Intent intent = new Intent(this, AnActivity.class);
startActivity(intent);
}
public void goToAnotherActivity(View view) {
Intent intent = new Intent(this, AnotherActivity.class);
startActivity(intent);
}
장점:즉시 제작이 용이하고 모듈식이며 여러 개를 쉽게 설정할 수 있습니다.onClick
같은 취지로
단점:검토 시 가독성이 어렵습니다.
- 할당
OnClickListener()
익명의 수업을 통해.(중간)
이별도설경는우다니입정하로는을 입니다.setOnClickListener()
button
각각을 오버라이드합니다.onClick()
그 나름의 목적을 가지고
Java 클래스:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), AnActivity.class);
view.getContext().startActivity(intent);}
});
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), AnotherActivity.class);
view.getContext().startActivity(intent);}
});
장점:즉석에서 쉽게 만들 수 있습니다.
단점:익명 수업이 많아 복습 시 가독성이 어려워질 것입니다.
- 활범방법인스이터페위동는을 Wide
switch
진술아 (" 아님) ("Pro" 님)님)
이것은 당신이 사용할 때입니다.switch
에서 사단대설명한추에 있는 onClick()
모든 활동 단추를 관리하는 방법입니다.
Java 클래스:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
Intent intent1 = new Intent(this, AnActivity.class);
startActivity(intent1);
break;
case R.id.button2:
Intent intent2 = new Intent(this, AnotherActivity.class);
startActivity(intent2);
break;
default:
break;
}
장점:모든 버튼 인텐트가 하나로 등록되어 있어 버튼 관리가 용이함onClick()
방법
질문의 두 번째 부분인 데이터 전달은 Android 응용 프로그램에서 활동 간에 데이터를 전달하는 방법을 참조하십시오.
편집: "Pro"가 아님
사용자 보기 활동에 대한 의도를 만들고 사용자 전달ID(예: 데이터베이스 조회).
Intent i = new Intent(getBaseContext(), ViewPerson.class);
i.putExtra("PersonID", personID);
startActivity(i);
그런 다음 View Person Activity에서 추가 데이터 번들을 가져와 null이 아닌지 확인한 다음(가끔 데이터를 전달하지 않는 경우) 데이터를 가져올 수 있습니다.
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
personID = extras.getString("PersonID");
}
이제 두 활동 간에 데이터를 공유해야 하는 경우 글로벌 싱글톤도 사용할 수 있습니다.
public class YourApplication extends Application
{
public SomeDataClass data = new SomeDataClass();
}
그런 다음 모든 활동에서 다음과 같이 호출합니다.
YourApplication appState = ((YourApplication)this.getApplication());
appState.data.CallSomeFunctionHere(); // Do whatever you need to with data here. Could be setter/getter or some other type of logic
사용자가 버튼을 클릭하면 XML 바로 안쪽에 다음과 같이 표시됩니다.
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextButton"
android:onClick="buttonClickFunction"/>
속성을 사용하여 상위 활동에 있어야 하는 메서드 이름을 선언합니다.그래서 저는 우리의 활동 안에서 다음과 같은 방법을 만들어야 합니다.
public void buttonClickFunction(View v)
{
Intent intent = new Intent(getApplicationContext(), Your_Next_Activity.class);
startActivity(intent);
}
Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);
Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);
startActivity(in);
This is an explicit intent to start secondscreen activity.
엠마누엘,
활동을 시작하기 전에 추가 정보를 입력해야 합니다. 그렇지 않으면 다음 활동의 onCreate 메서드에서 데이터에 액세스하는 경우 데이터를 아직 사용할 수 없습니다.
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value);
CurrentActivity.this.startActivity(myIntent);
이 간단한 방법을 사용해 보세요.
startActivity(new Intent(MainActivity.this, SecondActivity.class));
코틀린
첫 번째 활동
startActivity(Intent(this, SecondActivity::class.java)
.putExtra("key", "value"))
두 번째 활동
val value = getIntent().getStringExtra("key")
제안.
항상 키를 항상 일정한 파일에 저장하여 보다 효율적으로 관리할 수 있습니다.
companion object {
val PUT_EXTRA_USER = "user"
}
startActivity(Intent(this, SecondActivity::class.java)
.putExtra(PUT_EXTRA_USER, "value"))
보내는 활동에서 다음 코드를 시도합니다.
//EXTRA_MESSAGE is our key and it's value is 'packagename.MESSAGE'
public static final String EXTRA_MESSAGE = "packageName.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
....
//Here we declare our send button
Button sendButton = (Button) findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//declare our intent object which takes two parameters, the context and the new activity name
// the name of the receiving activity is declared in the Intent Constructor
Intent intent = new Intent(getApplicationContext(), NameOfReceivingActivity.class);
String sendMessage = "hello world"
//put the text inside the intent and send it to another Activity
intent.putExtra(EXTRA_MESSAGE, sendMessage);
//start the activity
startActivity(intent);
}
수신 활동에서 다음 코드를 시도합니다.
protected void onCreate(Bundle savedInstanceState) {
//use the getIntent()method to receive the data from another activity
Intent intent = getIntent();
//extract the string, with the getStringExtra method
String message = intent.getStringExtra(NewActivityName.EXTRA_MESSAGE);
그런 다음 AndroidManifest.xml 파일에 다음 코드를 추가합니다.
android:name="packagename.NameOfTheReceivingActivity"
android:label="Title of the Activity"
android:parentActivityName="packagename.NameOfSendingActivity"
Intent i = new Intent(firstactivity.this, secondactivity.class);
startActivity(i);
다른 활동에서 활동을 시작하는 것은 안드로이드 애플리케이션에서 매우 일반적인 시나리오입니다.
활동을 시작하려면 Intent 개체가 필요합니다.
의도 객체를 만드는 방법?
의도 객체는 생성자에서 두 개의 매개 변수를 사용합니다.
- 맥락
- 시작할 활동의 이름입니다.(또는 전체 패키지 이름)
예:
를 들어,두 활동이 , 를 들어, 들어예를두한면, 만당신가 활다동을지이래그서약,ities한다▁activ▁so면▁say,HomeActivity
그리고.DetailActivity
그리고 당신은 시작하기를 원합니다.DetailActivity
HomeActivity
(홈 활동-->상세 활동).
다음은 Detail Activity를 시작하는 방법을 보여주는 코드 조각입니다.
홈 활동.
Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);
그리고 당신은 끝났습니다.
버튼으로 되돌아와서 파트를 클릭합니다.
Button button = (Button) findViewById(R.id.someid);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);
}
});
새로운 활동을 시작하는 방법은 의도를 브로드캐스트하는 것이며, 한 활동에서 다른 활동으로 데이터를 전달하는 데 사용할 수 있는 특정한 종류의 의도가 있습니다.제가 추천하는 것은 당신이 의도와 관련된 안드로이드 개발자 문서를 확인하는 것입니다. 그것은 그 주제에 대한 풍부한 정보이고 예시도 가지고 있습니다.
다음 코드를 사용할 수 있습니다.
Intent myIntent = new Intent();
FirstActivity.this.SecondActivity(myIntent);
이 활동에서 다른 활동을 시작하고 번들 개체를 통해 매개 변수를 전달할 수도 있습니다.
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);
다른 활동의 데이터 검색(사용자 활동)
String s = getIntent().getStringExtra("USER_NAME");
Kotlin에서 /*로 할 수 있습니다. 첫 번째 활동에서 활동 레이아웃에 ID가 있는 단추가 있습니다.한 활동에서 다른 활동으로 데이터를 문자열 유형으로 전달해야 한다고 가정합니다 */
val btn = findViewById<Button>(R.id.button)
btn.setOnClickListener {
val intent = Intent(baseContext, SecondActivity::class.java).apply {
putExtra("KEY", data)
}
startActivity(intent)
}
두 번째 활동에서는 다음과 같이 다른 활동에서 데이터를 얻을 수 있습니다.
val name = intent.getStringExtra("KEY")
사용자 지정 개체를 전달해야 하는 경우 이 개체를 구획할 수 있어야 합니다.한 활동에서 다른 활동으로 전달해야 하는 클래스 콜라주 유형이 있음 */
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
class Collage(val name: String, val mobile: String, val email: String) : Parcelable
활동 먼저, 여기서 데이터가 콜라주 유형이라고 합니다.다른 활동으로 넘어가야 합니다*/
val btn = findViewById<Button>(R.id.button)
btn.setOnClickListener {
val intent = Intent(baseContext, SecondActivity::class.java).apply {
putExtra("KEY", data)
}
startActivity(intent)
}
그러면 두 번째 활동에서 우리는 다음과 같이 얻을 것입니다.
val item = intent.extras?.getParcelable<Collage>("KEY")
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SplashActivity.this,HomeActivity.class);
startActivity(intent);
}
});
보기를 구현합니다.ClickListener 인터페이스에서 onClick 메서드를 재정의합니다.
ImageView btnSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search1);
ImageView btnSearch = (ImageView) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearch: {
Intent intent = new Intent(Search.this,SearchFeedActivity.class);
startActivity(intent);
break;
}
이미 적절한 답이 제공되었지만, 저는 코틀린 언어로 답을 찾기 위해 왔습니다.이 질문은 특정 언어에 대한 질문이 아니므로 코틀린 언어로 이 작업을 수행하기 위해 코드를 추가합니다.
앤드리드를 위해 코틀린에서 이것을 하는 방법은 다음과 같습니다.
testActivityBtn1.setOnClickListener{
val intent = Intent(applicationContext,MainActivity::class.java)
startActivity(intent)
}
버튼 클릭 시 활동을 여는 가장 간단한 방법은 다음과 같습니다.
- res 폴더 아래에 두 개의 활동을 만들고, 첫 번째 활동에 단추를 추가하고, 이름을 지정합니다.
onclick
기능. - 각 활동에 대해 두 개의 Java 파일이 있어야 합니다.
- 다음은 코드입니다.
기본 활동.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void goToAnotherActivity(View view) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
두 번째 활동.java
package com.example.myapplication;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
}
}
AndroidManifest.xml(이 코드 블록을 기존에 추가하기만 하면 됨)
</activity>
<activity android:name=".SecondActivity">
</activity>
먼저 xml의 버튼을 입력합니다.
<Button
android:id="@+id/pre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"
android:text="Your Text"
/>
단추를 귀 기울이도록 합니다.
pre.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
버튼을 클릭한 경우:
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent= new Intent(getApplicationContext(), NextActivity.class);
intent.putExtra("data", value); //pass data
startActivity(intent);
}
});
다음에서 추가 데이터 수신NextActivity.class
:
Bundle extra = getIntent().getExtras();
if (extra != null){
String str = (String) extra.get("data"); // get a object
}
첫 번째 활동에서 코드를 작성합니다.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondAcitvity.class);
//You can use String ,arraylist ,integer ,float and all data type.
intent.putExtra("Key","value");
startActivity(intent);
finish();
}
});
두 번째 Activity.class에서
String name = getIntent().getStringExtra("Key");
버튼 위젯을 아래와 같이 xml로 배치
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
/>
그런 다음 아래와 같은 활동에서 청취자를 클릭하여 초기화하고 처리합니다.
In Activity On Create 메서드:
Button button =(Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new
Intent(CurrentActivity.this,DesiredActivity.class);
startActivity(intent);
}
});
오래된 질문이지만 표시된 페이지를 전환하는 것이 목표라면 페이지를 전환할 때 한 가지 활동만 수행하고 ContentView()를 호출합니다(일반적으로 사용자가 단추를 클릭하면 응답함).이를 통해 한 페이지의 내용을 다른 페이지로 간단히 호출할 수 있습니다.추가 소포 묶음이나 데이터를 주고받으려는 의도적인 광기는 없습니다.
저는 평소와 같이 페이지를 여러 개 작성하지만 각 페이지에 대해 활동을 만들지는 않습니다.필요에 따라 setContentView()를 사용하여 전환합니다.
Create()에 대한 유일한 기능은 다음과 같습니다.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater layoutInflater = getLayoutInflater();
final View mainPage = layoutInflater.inflate(R.layout.activity_main, null);
setContentView (mainPage);
Button openMenuButton = findViewById(R.id.openMenuButton);
final View menuPage = layoutInflatter.inflate(R.layout.menu_page, null);
Button someMenuButton = menuPage.findViewById(R.id.someMenuButton);
openMenuButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(menuPage);
}
});
someMenuButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
do-something-interesting;
setContentView(mainPage);
}
}
}
앱을 종료하기 전에 Back(뒤로) 버튼을 사용하여 내부 페이지로 돌아가려면, 컨텐츠 뷰() 세트를 랩핑하여 페이지를 작은 페이지 스택에 저장하고 BackPressed() 핸들러에 해당 페이지를 팝합니다.
버튼 xml:
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="jump to activity b"
/>
주 활동.java:
Button btn=findViewVyId(R.id.btn);
btn.setOnClickListener(btnclick);
btnclick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(Mainactivity.this,b.class);
startActivity(intent);
}
});
코틀린 2022
가장 간단한 방법:
val a = Intent(this.context, BarcodeActivity::class.java)
a.putExtra("barcode", barcode)
startActivity(a)
반대쪽(내 경우 바코드 활동):
val intent: Intent = intent
var data = intent.getStringExtra("barcode")
여기서 더 읽기
imageView.setOnClickListener(v -> {
// your code here
});
언급URL : https://stackoverflow.com/questions/4186021/how-to-start-new-activity-on-button-click
'programing' 카테고리의 다른 글
어떻게 "순서별" 필터링 순서 (0) | 2023.08.23 |
---|---|
데이터 사전 mariadb에서 참조 테이블을 찾을 수 없습니다. (0) | 2023.06.04 |
AppFabric이 다시 시작해도 제대로 복구되지 않음 (0) | 2023.06.04 |
다음 작업을 수행할 수 있습니까?각각의 루프를 거꾸로? (0) | 2023.06.04 |
응용 프로그램이 메인 스레드에서 너무 많은 작업을 수행하고 있을 수 있습니다. (0) | 2023.06.04 |