I am trying to build sample Android app in which the main activity contains a YouTubePlayerFragment. I get no errors with my implementation, but when I run this app on an AVD or my phone, the fragment for the YouTubePlayerFragment is just a black box. No video loads.
Any help is greatly appreciated.
Here is my code:
YouTubeFragment.java
package androidsample.example.com.fragments1;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerFragment;
public class YouTubeFragment extends YouTubePlayerFragment implements YouTubePlayer.OnInitializedListener {
// TODO: Rename and change types and number of parameters
public static YouTubeFragment newInstance() {
YouTubeFragment fragment = new YouTubeFragment();
return fragment;
}
private void init(){
initialize(DeveloperKey.DEVELOPER_KEY, this);
}
public YouTubeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_main, container, false);
YouTubeFragment ytf = newInstance();
ytf.init();
//inside fragment use getFragmentManager instead of getFragmentSupportManager
getFragmentManager().beginTransaction()
.add(R.id.youTubePlayer, ytf)
.commit();
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo("nCgQDjiotG0");
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(getActivity(), "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
}
MainActivity.java
package androidsample.example.com.fragments1;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youTubePlayer"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
I don't think you need to create a newInstance(). The instance is created in your xml. And when you are in onCreateView that is a specific instance already.
So you should be able to replace these lines
YouTubeFragment ytf = newInstance();
ytf.init();
With
this.init();
Or more simply
init();
With some help, I have a working version of this (problems with target SDK 21, using 19):
YouTubeFailureRecoveryActivity.java
package androidsample.example.com.fragments2;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerFragment;
public class YouTubeFailureRecoveryActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
//String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
String errorMessage = "custom ERror MessAgE";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider arg0, YouTubePlayer player,
boolean wasRestored) {
// TODO Auto-generated method stub
if (!wasRestored) {
player.cueVideo("nCgQDjiotG0");
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
// TODO Auto-generated method stub
return (YouTubePlayerFragment) getFragmentManager().findFragmentById(
R.id.youtube_fragment);
}
}
MainActivity.java
package androidsample.example.com.fragments2;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.youtube.player.YouTubePlayerFragment;
public class MainActivity extends YouTubeFailureRecoveryActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerFragment youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(DeveloperKey.DEVELOPER_KEY, 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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<fragment
android:id="#+id/youtube_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Related
Please see below my code: I have tried several codes that fulllscreen for videos and I did not succeed, or I did not know how to install.
I need enable fullscreen for videos for any player video
package com.androidapp.www.WEBSITE;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
WebView wv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv = (WebView)findViewById(R.id.webView);
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
wv.loadUrl("https://www.mfshd.net");
wv.setWebViewClient(new MobWebViewClient());
}
#Override
public void onBackPressed() {
if(wv.canGoBack()){
wv.goBack();
}else{
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MobWebViewClient extends WebViewClient {
}
}
Firstly you have to add a FrameLayout in your activity_main and make its visibility "gone"
Secondly add this code to your MainActivity:
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
wv.setWebChromeClient(new WebChromeClient() {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomView = view;
wv.setVisibility(View.GONE);
frameLayout.setVisibility(View.VISIBLE);
frameLayout.addView(view);
mCustomViewCallback = callback;
}
#Override
public void onHideCustomView() {
super.onHideCustomView();
if (mCustomView == null)
return;
wv.setVisibility(View.VISIBLE);
frameLayout.setVisibility(View.GONE);
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
frameLayout.removeView(mCustomView);
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
});
The app crashes when i tried to test, i am using fragments to create the app:
App crashed
I have this in audioFragment.java:
package amaguenet.com.reproductorxassidas;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.media.MediaPlayer;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class audioFragment extends Fragment {
// variable declaration
private ListView mainList;
private MediaPlayer mp;
private final String[] listContent = {"Ahonzubilahi Min Mayli", "Ajabani Khayru Baqin", "Ajabani Rabbu Sama", "Ala Innani Usni",
"Alal Muntaqa Khayril Baraya"};
private final int[] resID = {R.raw.ahonzu_bilahi_min_mayli, R.raw.ajabani_khayru_baqin, R.raw.ajabani_rabbu_sama,
R.raw.ala_innani_usni, R.raw.alal_muntaqa_khayril_baraya};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_audio, container, false);
// Initializing variables
mp = new MediaPlayer();
mainList = (ListView) v.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, listContent);
mainList.setAdapter(adapter);
mainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
playSong(position);
}
});
return v;
}
public void playSong(int songIndex) {
// Play song
mp.reset();// stops any current playing song
mp = MediaPlayer.create(getActivity().getApplicationContext(), resID[songIndex]);// create's
// new
// mediaplayer
// with
// song.
mp.start(); // starting mediaplayer
}
#Override
public void onDestroy() {
super.onDestroy();
mp.release();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public interface OnFragmentInteractionListener {
}
}
And this in a in fragment_audio (the layout):
<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"
tools:context="amaguenet.com.reproductorxassidas.audioFragment"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
Can some helps with this, i am using Fragments in Android Studio?
You can use getIdentifier() method, here is a simple example:
private final int resID = getContext().getResources().getIdentifier(direction, "raw", PACKAGE_NAME);
direction - string with your file name f.e: "ahonzu_bilahi_min_mayli"
PACKAGE_NAME - is your package name
Hi i'm new here and firstly i want to apologise for my language .I wanted to create my first android app ,and im curently struggle with some issues.
MainActivity ,which represents my main screen containing two buttons and spinner.In spinner user can choose one text file and after selection spinnerActivity should be triggered(screen with opened text file).I found problem because not every record from spinner trigger activity with text file that i want (one trigger file that i want and other trigger screen with empty TextView). Here is layout of spinnerActivity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="#+id/textView2"
android:layout_width="199dp"
android:layout_height="89dp"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text="nie dziala" />
<TextView
android:id="#+id/proximityTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0.0"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Code of MainACtivity
package com.example.myapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class MainActivity extends ActionBarActivity implements OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button click=(Button)findViewById(R.id.button2);
click.setOnClickListener(new View.OnClickListener(){ //nowy actionlistener
#Override
public void onClick(View v) {
Intent activitylauncher=new Intent(MainActivity.this,AboutActivity.class);
//tworzenie nowej intencji Create an intent for a specific component.
startActivity(activitylauncher);
}
});
final Button click2=(Button)findViewById(R.id.button1);
click2.setOnClickListener(new View.OnClickListener() { //nowy actionlistener
#Override
public void onClick(View v) {
Intent activitylauncher=new Intent(MainActivity.this,RandomActivity.class);
//tworzenie nowej intencji Create an intent for a specific component.
startActivity(activitylauncher);
}
});
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.recipie_array, android.R.layout.simple_spinner_item);
// Specify the layut to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// String i=Integer.toString(pos);
if(pos==1)
{
Intent intent3 = new Intent(MainActivity.this, SpinnerActivity.class);
intent3.putExtra("txt",(pos));
startActivity(intent3);
}
if(pos==2)
{
Intent intent3 = new Intent(MainActivity.this, SpinnerActivity.class);
startActivity(intent3);
}
if(pos==1)
{
Intent intent3 = new Intent(MainActivity.this, SpinnerActivity.class);
startActivity(intent3);
}
}
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and the code of spinneractivity
package com.example.myapp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class SpinnerActivity extends ActionBarActivity implements SensorEventListener {
TextView proxText;
SensorManager sm;
Sensor proxSensor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner);
//proximitymeter
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
proxSensor=sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
proxText=(TextView)findViewById(R.id.proximityTextView);
sm.registerListener(this,proxSensor,SensorManager.SENSOR_DELAY_NORMAL);
Intent intent3 = getIntent();
int value = intent3.getIntExtra("txt", 0);
//finish();
if (value==1)
{
open("przepis1.txt");
}
if (value==2)
{
open("przepis2.txt");
}
if (value==3)
{
open("przepis3.txt");
}
}
public void open(String name){
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,name);
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader bufor = new BufferedReader(new FileReader(file));
String line;
while ((line = bufor.readLine()) != null) {
text.append(line);
text.append('\n');
}
bufor.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.textView2);
//Set the text
tv.setText(text);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.spinner, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
//proxText.setText(String.valueOf(event.values[0]));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
Can someone look at this and help me with finding bugs?Thanks
Position starts form 0, I think problem is with the conditions,
You can write like this-
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Intent intent = new Intent(MainActivity.this, SpinnerActivity.class);
intent.putExtra("txt", pos + 1);
startActivity(intent);
}
I have this OnLongClickListener which is not getting fired. I think I have setup everything correctly and it has worked with a contextmenu before but right now it's not firing and the log is not even giving me any error.
I really hope you can give me any ideas. It is probably a silly mistake somewhere.
package fragments;
import interfaces.AsyncTaskCompleteListener;
import java.util.List;
import com.example.slidingmenu.R;
import dialog.EditDialog;
import services.GetRequest;
import model.Post;
import adapter.PostAdapter;
import android.os.Bundle;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class HomeFragment extends Fragment implements AsyncTaskCompleteListener, View.OnLongClickListener {
private ListView mainListView;
private GetRequest service;
private ProgressDialog dialog;
private ActionMode mActionMode;
public HomeFragment() {}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedIntanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
mainListView = (ListView) rootView.findViewById(R.id.mainListView);
mainListView.setOnLongClickListener(this);
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Please wait...");
service = new GetRequest(this);
service.execute();
dialog.show();
registerForContextMenu(mainListView);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch(item.getItemId()) {
case R.id.edit:
Log.d("edit", "pressed");
FragmentManager fragmentManager = getFragmentManager();
EditDialog editDialog = new EditDialog();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.add(android.R.id.content, editDialog).addToBackStack(null).commit();
mode.finish();
return true;
default:
return false;
}
}
};
#Override
public boolean onLongClick(View v) {
Toast.makeText(getActivity(), "PRESSED", Toast.LENGTH_SHORT).show();
Log.d("hey", "pressed");
if(mActionMode != null) {
return false;
}
mActionMode = getActivity().startActionMode(mActionModeCallback);
mainListView.setSelected(true);
return true;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
Toast.makeText(getActivity(), "Refresh!", Toast.LENGTH_SHORT).show();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Please wait while refreshing...");
dialog.show();
service = new GetRequest(this);
service.execute();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTaskComplete(List<Post> posts) {
PostAdapter adapter = new PostAdapter(getActivity(), R.layout.listview_item_row, posts);
LayoutInflater inflater = (LayoutInflater)getActivity().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View header = (View)inflater.inflate(R.layout.listview_header_row, null);
if(mainListView.getHeaderViewsCount() == 0) {
mainListView.addHeaderView(header);
}
mainListView.setAdapter(adapter);
if(dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public void onTaskComplete(String result) {
// TODO Auto-generated method stub
}
}
Here is the xml file where I have my ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainListView"
android:longClickable="true"
android:clickable="true"
></ListView>
</LinearLayout>
You are attaching a listener to the entire view instead of each row. I'm not sure why nothing is being fired, but those touch events are probably being intercepted by other views.
Instead of ListView.setOnLongClickListener(), you should use ListView.setOnItemLongClickListener().
Here is the link for the Android Docs for this method.
Since you are registerForContextMenu for your listview already. setOnLongClickListener is not longer needed. What you needs is onCreateContextMenu method and onContextItemSelected.
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
// create menu item here
}
#Override
public boolean onContextItemSelected(MenuItem item){
// do your long click listener here
}
Here is the library: https://github.com/astuetz/PagerSlidingTabStrip
I'm trying to implement it but my app keeps crashing on startup. I've tried to understand the sample app that is posted but don't think I'm doing something right. Here is my code:
MainActivity.java
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.astuetz.PagerSlidingTabStrip;
public class MainActivity extends FragmentActivity {
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
}
private Drawable.Callback drawableCallback = new Drawable.Callback() {
#Override
public void invalidateDrawable(Drawable who) {
getActionBar().setBackgroundDrawable(who);
}
#Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
handler.postAtTime(what, when);
}
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
handler.removeCallbacks(what);
}
};
public class MyPagerAdapter extends FragmentPagerAdapter{
private final String[] TITLES = {"T1","T2"};
public MyPagerAdapter(FragmentManager fm){
super(fm);
}
public CharSequence getPageTitle(int position){
return TITLES[position];
}
#Override
public Fragment getItem(int i) {
return null;
}
#Override
public int getCount() {
return TITLES.length;
}
}
}
And here is activity_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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="edu.purdue.test.app.MainActivity">
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
tools:context=".MainActivity" />
</RelativeLayout>
You're not instantiating any of the fragments you wish to become tabs in the FragmentPagerAdapter, getItem method. Instead you're returning null and therefore there are no views to fill the viewpager. I can see you've checked out his sample project, maybe take a closer look at the fragments you're trying to add to the viewpager. The above answer looks like a sound implementation.
Here is an example that I am using right now,
public class Formulario extends FragmentActivity implements ActionBar.TabListener {
private static final FragmentTransaction transaction = null;
public String ambitorec;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "tab 1", "tab 2", "tab 3" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_formulario);
ambitorec = getIntent().getStringExtra("ambito");
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
also you need to add the adapter, in this case :
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// tab 1 fragment activity
return new Formulario1Fragment();
case 1:
// tab2 fragment activity
return new Formulario2Fragment();
case 2:
// tab 3 fragment activity
return new MultimediaFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
hope it helps, if you need more help ill try to explain
In FragmentPagerAdapter#getItem, you are not instantiating any of the fragments you want to become tabs. Instead of returning a fragment, you're returning null, which means there are no views to fill the viewpager. I see you've looked over his sample project, so look over the fragments you're trying to add to the viewpager again. The above response appears to be a second implementation.