Java 如何访问片段并将其更改为主要活动
我有一个Java 如何访问片段并将其更改为主要活动,java,android,android-studio,Java,Android,Android Studio,我有一个Activity Main类和XML,还有ana_sayfa(Fragment)类和XML 当我滑动屏幕并显示ana_sayfa时,我想将项目添加到可扩展的列表视图中,但我无法将ana_sayfa片段访问到主活动类中 主要活动类别: 使用setArguments(Bundle)将数据传递给片段,并使用getArguments()在onCreateView()中检索数据。然后片段可以处理列表视图中呈现数据的所有逻辑。您可以使用接口在活动和片段之间进行通信。例如,在片段类中,可以添加: pu
Activity Main
类和XML
,还有ana_sayfa
(Fragment
)类和XML
当我滑动屏幕并显示ana_sayfa
时,我想将项目添加到可扩展的列表视图中,但我无法将ana_sayfa
片段访问到主活动类中
主要活动类别:
使用
setArguments(Bundle)
将数据传递给片段,并使用getArguments()
在onCreateView()中检索数据。然后片段可以处理列表视图中呈现数据的所有逻辑。您可以使用接口
在活动和片段之间进行通信。例如,在片段类中,可以添加:
public class F_ana_sayfa extends Fragment {
...
SomeInterface myInterface;
// Container activity must implement this interface
public interface SomeInterface {
// You can define your interface functions here
void doSomething();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
myInterface = (SomeInterface) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement SomeInterface");
}
}
public void someFunction(boolean someBoolean) {
if (someBoolean) {
// Calling the interface function
myInterface.doSomething();
}
}
}
现在,您的活动必须实现fragment类中定义的接口。
例如:
public class MainActivity extends AppCompatActivity implements F_ana_sayfa.SomeInterface {
...
public void doSomething() {
// Your code here
}
}
欲了解更多信息,请访问
public class F_ana_sayfa extends Fragment {
...
SomeInterface myInterface;
// Container activity must implement this interface
public interface SomeInterface {
// You can define your interface functions here
void doSomething();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
myInterface = (SomeInterface) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement SomeInterface");
}
}
public void someFunction(boolean someBoolean) {
if (someBoolean) {
// Calling the interface function
myInterface.doSomething();
}
}
}
public class MainActivity extends AppCompatActivity implements F_ana_sayfa.SomeInterface {
...
public void doSomething() {
// Your code here
}
}