से फ्रैगमेंट का दृश्य प्राप्त करें मेरे पास FragmentActivity
है जहां मैं Fragment
जोड़ता हूं। कुछ स्थितियों के आधार पर, मैं उस खंड के लेआउट से Buttons
तक पहुंच बनाना चाहता हूं और उनमें से श्रोताओं को क्लिक करना चाहता हूं।फ्रैगमेंट एक्टिविटी
मैं क्या है:
View view = myFragment.getView();
Button myButton = (Button) view.findViewById(R.id.my_button);
myButton.setOnClickListener(new MyClickListener());
लेकिन view
वैरिएबल हमेशा null
है।
मैं गतिविधि का दृश्य कैसे प्राप्त कर सकता हूं?
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class DetailFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details, container, false);
return view;
}
public void setSettings(){
Button button = (Button) getView().findViewById(R.id.my_button);
button.setOnClickListener(new MyClickListener());
}
}
क्या मेराफ्रेम जोड़ा गया है और दृश्यमान है? –
ध्यान दें कि आप अपनी गतिविधि के दृश्य पदानुक्रम पर 'findViewById()' को कॉल कर रहे हैं, न कि 'view''। – laalto
जब आप करते हैं: 'बटन myButton = (बटन) findViewById (R.id.my_button);', आप अपने वर्तमान दृश्य के लिए बटन ढूंढने का प्रयास करें जो आपका 'खंड दृश्य' नहीं है। इसलिए यह उम्मीद के रूप में काम नहीं कर रहा है। –